package com.yami.shop.api.listener;

import java.util.Map;

/**
 * @author DELL
 */
public class SimilarityCalculator {

    /**
     * 实现余弦相似度算法
     * @param item1
     * @param item2
     * @return
     */
    public static double cosineSimilarity(Map<Long, Double> item1, Map<Long, Double> item2) {
        double dotProduct = 0.0;
        double norm1 = 0.0;
        double norm2 = 0.0;

        for (Long userId : item1.keySet()) {
            if (item2.containsKey(userId)) {
                dotProduct += item1.get(userId) * item2.get(userId);
            }
            norm1 += Math.pow(item1.get(userId), 2);
        }

        for (Double value : item2.values()) {
            norm2 += Math.pow(value, 2);
        }

        return dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2));
    }
}
